package com.chookss.home.audit.shop;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.ReimbursementDetailEntity;
import com.chookss.tools.FileUtilss;
import com.chookss.tools.GridSpacingItemDecoration;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.PathUtil;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.GlideEngine;
import com.chookss.view.ImageFileCompressEngine;
import com.chookss.view.MyRoundLayout;
import com.google.gson.reflect.TypeToken;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.luck.picture.lib.animators.AnimationType;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.lvgroup.hospital.base.BaseAct;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ShopServiceActivity extends BaseAct {
    //物品维修服务
    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.edContent)
    EditText edContent;
    @BindView(R.id.tvSure)
    TextView tvSure;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    private String goodsCode = "",goodsName="";
    private MyImagsAdapter adapter;
    private List<String> list = new ArrayList<>();
    private ArrayList<Map<String, String>> urlListMaps = new ArrayList<>();
    private int numAll = 0;
    private String baoixaoTypeCode="",baoixaoTypeName="",repairCode="",workflowId="";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_service);
        ButterKnife.bind(this);
        initState();
    }

    @Override
    public void initData() {
        commonTitleTxt.setText("申请维修");
        goodsCode = getIntent().getStringExtra("goodsCode");
        goodsName = getIntent().getStringExtra("goodsName");
        repairCode = getIntent().getStringExtra("repairCode");
        workflowId = getIntent().getStringExtra("workflowId");
        baoixaoTypeCode = getIntent().getStringExtra("baoixaoTypeCode");
        baoixaoTypeName = getIntent().getStringExtra("baoixaoTypeName");
        if(!Utils.isNull(repairCode)){
            tvSure.setText("重新提交");
            selectGoodsInfDetail();
        }
        list.add("");
        GridLayoutManager gridLayoutManager1 = new GridLayoutManager(this, 3);
        recyclerView.setLayoutManager(gridLayoutManager1);
        GridSpacingItemDecoration gridSpacingItemDecoration = new GridSpacingItemDecoration(3, Utils.dip2px(this, 12), false);
        recyclerView.addItemDecoration(gridSpacingItemDecoration);
        adapter = new MyImagsAdapter(R.layout.item_my_news, this, list);
        recyclerView.setAdapter(adapter);
    }
    private void selectGoodsInfDetail() {
        //审批基本数据
        Map<String, String> map = new HashMap<>();
        map.put("repairCode", repairCode);
        map.put("type", "12");   // 1-新闻 2-视频 3-补卡 4-请假 5-外勤 6-图文7报销8物料9借款
        showLoading();
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<ReimbursementDetailEntity>>() {
        }.getType(), null, Urls.selectRepairDeail, SignUtils2.makeSignStr(map), false, new ObserverCallback<ReimbursementDetailEntity>() {
            @Override
            public void onSuccess(ReimbursementDetailEntity data) {
                dismissLoading();
                if (data != null) {
                    if (tvSure == null) {
                        return;
                    }
                    goodsCode=data.getGoodsCode();
                    goodsName=data.getGoodsName();
                    baoixaoTypeCode=data.getBaoixaoTypeCode();
                    baoixaoTypeName=data.getBaoixaoTypeName();
                   edContent.setText(data.getRemark());
                    list.clear();
                    for (int i = 0; i < data.getAnnexs().get(0).getPictureInfoList().size(); i++) {
                        list.add(data.getAnnexs().get(0).getPictureInfoList().get(i).getPictureUrl());
                    }
                    if(list.size()<9){
                        list.add("");
                    }
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(String errorMsg) {
                dismissLoading();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }
    private void uploadPicData() {
        String picUrl = list.get(numAll);
        if (Utils.isNull(picUrl)) {
            numAll++;
            if (numAll == list.size()) {
                //图片上传完毕
                uploadData();
            }
        } else {
            int y = numAll;
            if (picUrl.startsWith("http")) {
                numAll++;
                urlListMaps.get(y).put("picturePath", picUrl);
                if (numAll == list.size()) {
                    //图片上传完毕
                    uploadData();
                }
            } else {
                File file = new File(picUrl);
                MyHttpRequest.uploadPicture(Urls.uploadPicture, this, "2", file, new JsonCallback<String>() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        JSONObject result = null;
                        JSONObject data = null;
                        try {
                            result = new JSONObject(response.body().toString());
                            if (result.getString("code").equals("200")) {
                                data = result.getJSONObject("data");
                                numAll++;
                                FileUtilss.delFile(picUrl);
                                urlListMaps.get(y).put("picturePath", data.getString("originalUrl"));
                                if (numAll == list.size()) {
                                    //图片上传完毕
                                    uploadData();
                                }else{
                                    uploadPicData();
                                }
                            } else if (result.getString("code").startsWith("400")) {
                                dismissLoading();
                                OkGoUtil.onErrorIntent(result.getString("code"), result.getString("msg"));
                            } else {
                                dismissLoading();
                                MyToast.show(result.getString("msg"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            dismissLoading();
                            MyToast.show("图片上传失败，请稍后重试");
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissLoading();
                        MyToast.show("图片上传失败，请稍后重试");
                    }
                });
            }
        }
    }

    private void uploadData() {
        Map<String, Object> map = new HashMap<>();
        map.put("remark", edContent.getText().toString());
        map.put("type", "12");//12维修13交付
        map.put("goodsCode",goodsCode);
        map.put("orgCode", new ShareUtils().getString(this, StaticClass.BELG_ORG_CODE, ""));
        map.put("orgName",new ShareUtils().getString(this, StaticClass.BELG_ORG_NAME, ""));
        map.put("goodsName", goodsName);
        map.put("goodsNum", "1");
        map.put("baoixaoTypeCode", baoixaoTypeCode);
        map.put("baoxiaoTypeName", baoixaoTypeName);
        map.put("baoixaoTypeName", baoixaoTypeName);
        List<Map<String, String>> list = new ArrayList<>();
        Map<String, String> maps = new HashMap<>();
        String pictureUrl = "", fileUrl = "";
        maps.put("baoixaoTypeCode", "");
        maps.put("annexName", "图片");
        for (int i = 0; i < urlListMaps.size(); i++) {
            if (!Utils.isNull(urlListMaps.get(i).get("picturePath"))) {
                if (!Utils.isNull(fileUrl)) {
                    pictureUrl = pictureUrl + "," + urlListMaps.get(i).get("picturePath");
                } else {
                    pictureUrl = pictureUrl + urlListMaps.get(i).get("picturePath");
                }
            }
        }
        maps.put("fileUrl", "");
        maps.put("pictureUrl", pictureUrl);
        list.add(maps);
        map.put("annexs", XJson.listToJsArrays(list));
        String url="";
        if(!Utils.isNull(repairCode)){
            map.put("repairCode", repairCode);
            map.put("workflowId", workflowId);
            url=Urls.updateRepairGoodsInfo;
        }else{
            url=Urls.repairGoodsInfo;
        }
        MyHttpRequest.postRequestJson(url, this,  XJson.mapToJObj(map).toString(), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    dismissLoading();
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        MyToast.show("提交成功");
                        EventBus.getDefault().post(new MyEvent("RefreshShopRecord"));
                        finish();
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("提交失败，请稍后重试");
                }
            }
        });
    }

    private void requestCamera() {
        XXPermissions.with(this)
                .permission(Permission.CAMERA)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {
                            openCamera(10 - list.size());
                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(ShopServiceActivity.this, denied, quick);
                    }
                });
    }

    private void openCamera(int num) {
        PictureSelector.create(this)
                .openGallery(SelectMimeType.ofImage())
                .isDisplayCamera(true)//是否显示相机入口
                .setMaxSelectNum(num)
                .setSelectionMode(SelectModeConfig.MULTIPLE)//多选
                .isPreviewImage(true)//是否支持预览图片
                .setCompressEngine(ImageFileCompressEngine.createGlideEngine())
                .setRecyclerAnimationMode(AnimationType.SLIDE_IN_BOTTOM_ANIMATION)
                .setImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                // 如果是直接从相册获取
                List<LocalMedia> selectList = PictureSelector.obtainSelectorList(data);
                for (int i = 0; i < selectList.size(); i++) {
                    String url = "";
                    if (!Utils.isNull(selectList.get(i).getCompressPath())) {
                        if (selectList.get(i).getCompressPath().contains("content://")) {
                            Uri uri = Uri.parse(selectList.get(i).getCompressPath());
                            url = PathUtil.getPath(this, uri);
                        } else {
                            url = selectList.get(i).getCompressPath();
                        }
                    } else {
                        if (selectList.get(i).getPath().contains("content://")) {
                            Uri uri = Uri.parse(selectList.get(i).getPath());
                            url = PathUtil.getPath(this, uri);
                        } else {
                            url = selectList.get(i).getPath();
                        }
                    }
                    if (!list.contains(url)) {
                        list.add(0, url);
                    }
                    if (list.size() == 10) {
                        list.remove(9);
                    }
                }
                adapter.notifyDataSetChanged();
            }
        }

    }

    class MyImagsAdapter extends BaseQuickAdapter<String, BaseViewHolderEx> {
        private Context context;
        private int width, height;

        public MyImagsAdapter(int layoutResId, Context context, @io.reactivex.annotations.Nullable List<String> data) {
            super(layoutResId, data);
            this.context = context;
            width = (Utils.getScreenWidthPixel(context) - Utils.dip2px(context, 48)) / 3;
            height = width;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, String item) {
            MyRoundLayout myRl = helper.getView(R.id.myRl);
            ImageView ivBg = helper.getView(R.id.ivBg);
            LinearLayout llDelete = helper.getView(R.id.llDelete);
            LinearLayout llAdd = helper.getView(R.id.llAdd);
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) myRl.getLayoutParams();
            params.height = height;
            params.width = width;
            myRl.setLayoutParams(params);
            RelativeLayout.LayoutParams llAddParams = (RelativeLayout.LayoutParams) llAdd.getLayoutParams();
            llAddParams.height = height;
            llAddParams.width = width;
            llAdd.setLayoutParams(llAddParams);
            if (Utils.isNull(item)) {
                llAdd.setVisibility(View.VISIBLE);
                myRl.setVisibility(View.GONE);
            } else {
                llAdd.setVisibility(View.GONE);
                myRl.setVisibility(View.VISIBLE);
                Glide.with(ShopServiceActivity.this).load(item).into(ivBg);
            }
            llDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    list.remove(helper.getItemPosition());
                    if (list.size() < 9 && !Utils.isNull(list.get(list.size() - 1))) {
                        list.add("");
                    }
                    adapter.notifyDataSetChanged();
                }
            });
            llAdd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    requestCamera();
                }
            });

        }
    }

    @OnClick({R.id.common_title_back, R.id.tvSure})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.tvSure:
                if (Urls.antiShake.check()) {
                    return;
                }
                if (Utils.isNull(edContent.getText().toString())) {
                    MyToast.show("请输入维修原因");
                    return;
                }
                if (list.size() > 1) {
                    numAll = 0;
                    urlListMaps.clear();
                    for (int i = 0; i < list.size(); i++) {
                        Map<String, String> map = new HashMap<>();
                        map.put("picturePath", "");
                        map.put("thumbnailPath", "");
                        urlListMaps.add(map);
                    }
                    showLoading();
                    uploadPicData();
                } else {
                    showLoading();
                    uploadData();
                }

                break;
        }
    }

}
